<?php
require_once __DIR__ . '/../functions.php';

// 检查管理员权限
if (!isAdmin()) {
    redirect('../index.php', '您没有权限访问此页面', 'danger');
}

$db = getDB();

// 获取系统设置
$settings = [];
$stmt = $db->query("SELECT * FROM settings");
foreach ($stmt->fetchAll() as $setting) {
    $settings[$setting['key_name']] = $setting['key_value'];
}

// 定义快递查询相关变量 - 确保正确的类型转换
$expressBalance = isset($settings['express_balance']) && $settings['express_balance'] !== '' 
    ? floatval($settings['express_balance']) 
    : 0.00;
$expressBalanceUpdated = $settings['express_balance_updated'] ?? '';
$expressToken = $settings['express_token'] ?? '';
$expressApiUrl = $settings['express_api_url'] ?? 'https://music.wxnotes.cn/kd/';

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action == 'update_basic') {
        // 更新基本设置
        $siteName = $_POST['site_name'] ?? '';
        $siteDescription = $_POST['site_description'] ?? '';
        
        if (empty($siteName)) {
            $error = '网站名称不能为空';
        } else {
            // 更新设置
            $stmt = $db->prepare("INSERT INTO settings (key_name, key_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE key_value = ?");
            
            $stmt->execute(['site_name', $siteName, $siteName]);
            $stmt->execute(['site_description', $siteDescription, $siteDescription]);
            
            $success = '基本设置更新成功';
            
            // 更新本地变量
            $settings['site_name'] = $siteName;
            $settings['site_description'] = $siteDescription;
        }
    } elseif ($action == 'update_pushplus') {
        // 更新PushPlus设置
        $pushplusEnabled = isset($_POST['pushplus_enabled']) ? 1 : 0;
        $adminPushplusToken = $_POST['admin_pushplus_token'] ?? '';
        $adminPushplusEnabled = isset($_POST['admin_pushplus_enabled']) ? 1 : 0;
        
        $stmt = $db->prepare("INSERT INTO settings (key_name, key_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE key_value = ?");
        
        $stmt->execute(['pushplus_enabled', $pushplusEnabled, $pushplusEnabled]);
        $stmt->execute(['admin_pushplus_token', $adminPushplusToken, $adminPushplusToken]);
        $stmt->execute(['admin_pushplus_enabled', $adminPushplusEnabled, $adminPushplusEnabled]);
        
        $success = 'PushPlus设置更新成功';
        
        // 更新本地变量
        $settings['pushplus_enabled'] = $pushplusEnabled;
        $settings['admin_pushplus_token'] = $adminPushplusToken;
        $settings['admin_pushplus_enabled'] = $adminPushplusEnabled;
        
    } // 在 settings.php 的表单处理部分添加
    elseif ($action == 'update_approval') {
    $registrationApproval = isset($_POST['registration_approval']) ? 1 : 0;
    
    $stmt = $db->prepare("INSERT INTO settings (key_name, key_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE key_value = ?");
    $stmt->execute(['registration_approval', $registrationApproval, $registrationApproval]);
    
    $success = '注册审批设置更新成功';
    
    // 更新本地变量
    $settings['registration_approval'] = $registrationApproval;
}elseif ($action == 'update_express') {
    // 更新快递查询设置
    $expressToken = $_POST['express_token'] ?? '';
    $expressApiUrl = $_POST['express_api_url'] ?? '';
    $sfPhoneTail = $_POST['sf_phone_tail'] ?? '';
    
    if (empty($expressToken)) {
        $error = '快递查询Token不能为空';
    } else {
        // 验证顺丰手机尾号格式
        if (!empty($sfPhoneTail) && (!is_numeric($sfPhoneTail) || strlen($sfPhoneTail) !== 4)) {
            $error = '顺丰手机尾号必须是4位数字';
        } else {
            $stmt = $db->prepare("INSERT INTO settings (key_name, key_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE key_value = ?");
            
            $stmt->execute(['express_token', $expressToken, $expressToken]);
            $stmt->execute(['express_api_url', $expressApiUrl, $expressApiUrl]);
            $stmt->execute(['sf_phone_tail', $sfPhoneTail, $sfPhoneTail]);
            
            // 清除余额缓存 - 设置为0而不是空字符串
            $stmt->execute(['express_balance', '0.00', '0.00']);
            $stmt->execute(['express_balance_updated', '', '']);
            
            $success = '快递查询设置更新成功';
            
            // 更新本地变量
            $settings['express_token'] = $expressToken;
            $settings['express_api_url'] = $expressApiUrl;
            $settings['sf_phone_tail'] = $sfPhoneTail;
            $settings['express_balance'] = '0.00';
            $settings['express_balance_updated'] = '';
            
            // 更新快递查询相关变量
            $expressToken = $expressToken;
            $expressApiUrl = $expressApiUrl;
            $expressBalance = 0.00;
            $expressBalanceUpdated = '';
        }
    }
}
}

include __DIR__ . '/header.php';
?>

<!-- 其余HTML代码保持不变，但在显示余额的地方使用修复后的变量 -->

<!-- 其余HTML代码保持不变 -->


            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                <h1 class="h2">系统设置</h1>
            </div>

            <?php if (isset($error)): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="bi bi-exclamation-triangle-fill"></i> <?php echo htmlspecialchars($error); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <?php if (isset($success)): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="bi bi-check-circle-fill"></i> <?php echo htmlspecialchars($success); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <div class="row">
                <div class="col-lg-8">
                    <!-- 基本设置 -->
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5 class="mb-0">
                                <i class="bi bi-info-circle"></i> 基本设置
                            </h5>
                        </div>
                        <div class="card-body">
                            <form method="POST">
                                <input type="hidden" name="action" value="update_basic">
                                
                                <div class="mb-3">
                                    <label for="site_name" class="form-label">
                                        网站名称 <span class="text-danger">*</span>
                                    </label>
                                    <input type="text" class="form-control" id="site_name" name="site_name" 
                                           value="<?php echo htmlspecialchars($settings['site_name'] ?? '报单系统'); ?>" required>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="site_description" class="form-label">
                                        网站描述
                                    </label>
                                    <textarea class="form-control" id="site_description" name="site_description" 
                                              rows="3" placeholder="请输入网站描述"><?php echo htmlspecialchars($settings['site_description'] ?? ''); ?></textarea>
                                </div>
                                
                                <button type="submit" class="btn btn-primary">
                                    <i class="bi bi-save"></i> 保存设置
                                </button>
                            </form>
                        </div>
                    </div>

                    <!-- PushPlus设置 -->
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5 class="mb-0">
                                <i class="bi bi-bell"></i> PushPlus推送设置
                            </h5>
                        </div>
                        <div class="card-body">
                            <form method="POST">
                                <input type="hidden" name="action" value="update_pushplus">
                                
                                <div class="mb-3">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="pushplus_enabled" name="pushplus_enabled" 
                                               value="1" <?php echo ($settings['pushplus_enabled'] ?? 1) ? 'checked' : ''; ?>>
                                        <label class="form-check-label" for="pushplus_enabled">
                                            开启PushPlus推送功能
                                        </label>
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="admin_pushplus_token" class="form-label">
                                        管理员PushPlus密钥
                                        <a href="http://www.pushplus.plus/" target="_blank" class="small text-decoration-none">
                                            <i class="bi bi-question-circle"></i> 如何获取？
                                        </a>
                                    </label>
                                    <input type="text" class="form-control" id="admin_pushplus_token" name="admin_pushplus_token" 
                                           value="<?php echo htmlspecialchars($settings['admin_pushplus_token'] ?? ''); ?>"
                                           placeholder="请输入管理员的PushPlus密钥">
                                    <div class="form-text">
                                        设置后，管理员将收到新订单提交的推送通知
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="admin_pushplus_enabled" name="admin_pushplus_enabled" 
                                               value="1" <?php echo ($settings['admin_pushplus_enabled'] ?? 0) ? 'checked' : ''; ?>>
                                        <label class="form-check-label" for="admin_pushplus_enabled">
                                            管理员接收推送通知
                                        </label>
                                    </div>
                                </div>
                                
                                <button type="submit" class="btn btn-info text-white">
                                    <i class="bi bi-bell-fill"></i> 保存推送设置
                                </button>
                            </form>
                        </div>
                    </div>
                    
                    <!-- 在 settings.php 的 PushPlus设置 后面添加注册审批设置 -->
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5 class="mb-0">
                                <i class="bi bi-person-check"></i> 注册审批设置
                            </h5>
                        </div>
                        <div class="card-body">
                            <form method="POST">
                                <input type="hidden" name="action" value="update_approval">
                                
                                <div class="mb-3">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="registration_approval" name="registration_approval" 
                                               value="1" <?php echo ($settings['registration_approval'] ?? 0) ? 'checked' : ''; ?>>
                                        <label class="form-check-label" for="registration_approval">
                                            开启注册审批
                                        </label>
                                    </div>
                                    <div class="form-text">
                                        开启后，新注册的用户需要管理员审批才能登录
                                    </div>
                                </div>
                                
                                <button type="submit" class="btn btn-primary">
                                    <i class="bi bi-save"></i> 保存设置
                                </button>
                            </form>
                        </div>
                    </div>
                    
                   <!-- 快递查询设置 -->
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5 class="mb-0">
                                <i class="bi bi-truck"></i> 快递查询设置
                            </h5>
                        </div>
                        <div class="card-body">
                            <form method="POST">
                                <input type="hidden" name="action" value="update_express">
                                
                                <div class="mb-3">
                                    <label for="express_token" class="form-label">
                                        快递查询Token <span class="text-danger">*</span>
                                    </label>
                                    <input type="text" class="form-control" id="express_token" name="express_token" 
                                           value="<?php echo htmlspecialchars($expressToken); ?>" 
                                           placeholder="请输入快递查询API Token" required>
                                    <div class="form-text">
                                        请填写在快递查询系统注册后获取的Token
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="express_api_url" class="form-label">
                                        快递查询API地址
                                    </label>
                                    <input type="url" class="form-control" id="express_api_url" name="express_api_url" 
                                           value="<?php echo htmlspecialchars($expressApiUrl); ?>"
                                           placeholder="https://music.wxnotes.cn/kd/">
                                </div>
                                
                                <!-- 新增：顺丰手机尾号设置 -->
                                <div class="mb-3">
                                    <label for="sf_phone_tail" class="form-label">
                                        顺丰快递手机尾号（后4位）
                                    </label>
                                    <input type="text" class="form-control" id="sf_phone_tail" name="sf_phone_tail" 
                                           value="<?php echo htmlspecialchars($settings['sf_phone_tail'] ?? ''); ?>"
                                           maxlength="4" pattern="[0-9]{4}" placeholder="请输入顺丰快递收件人手机号后4位">
                                    <div class="form-text">
                                        设置后，所有顺丰快递查询将自动使用此手机尾号
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <div class="alert alert-info">
                                        <i class="bi bi-info-circle"></i>
                                        <strong>使用说明：</strong>
                                        <ul class="mb-0 mt-2">
                                            <li>Token需要在快递查询系统注册后获取</li>
                                            <li>系统会自动检查余额并更新订单签收状态</li>
                                            <li>支持单个、批量更新物流信息</li>
                                            <li>顺丰快递需要手机尾号后4位才能查询</li>
                                            <li>一次扣分0.009</li>
                                        </ul>
                                    </div>
                                </div>
                                
                                <div class="d-flex justify-content-between align-items-center">
                                    <button type="submit" class="btn btn-success">
                                        <i class="bi bi-save"></i> 保存快递设置
                                    </button>
                                    
                                    <?php if (!empty($expressToken)): ?>
                                    <div>
                                        <button type="button" class="btn btn-outline-primary" onclick="checkExpressBalance()">
                                            <i class="bi bi-currency-dollar"></i> 检查余额
                                        </button>
                                        <button type="button" class="btn btn-outline-info" onclick="testExpressConnection()">
                                            <i class="bi bi-wifi"></i> 测试连接
                                        </button>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </form>
                            
                            <?php if (!empty($expressToken)): ?>
                            <div class="mt-3 p-3 bg-light rounded">
                                <div class="row">
                                    <div class="col-md-6">
                                        <strong>当前余额：</strong>
                                        <span class="text-success fw-bold">¥<?php 
                                            $displayBalance = is_numeric($expressBalance) ? $expressBalance : 0.00;
                                            echo number_format($displayBalance, 2); 
                                        ?></span>
                                    </div>
                                    <div class="col-md-6">
                                        <strong>最后检查：</strong>
                                        <span class="text-muted">
                                            <?php echo $expressBalanceUpdated ? formatTime($expressBalanceUpdated) : '从未检查'; ?>
                                        </span>
                                    </div>
                                </div>
                                <?php if (!empty($settings['sf_phone_tail'])): ?>
                                <div class="row mt-2">
                                    <div class="col-12">
                                        <strong>顺丰手机尾号：</strong>
                                        <span class="text-info"><?php echo htmlspecialchars($settings['sf_phone_tail']); ?></span>
                                    </div>
                                </div>
                                <?php endif; ?>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- 系统信息 -->
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5 class="mb-0">
                                <i class="bi bi-info-circle"></i> 系统信息
                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <table class="table table-sm">
                                        <tr><td><strong>PHP版本：</strong></td><td><?php echo PHP_VERSION; ?></td></tr>
                                        <tr><td><strong>数据库版本：</strong></td><td>MySQL 5.7+</td></tr>
                                        <tr><td><strong>服务器时间：</strong></td><td><?php echo date('Y-m-d H:i:s'); ?></td></tr>
                                        <tr><td><strong>系统时区：</strong></td><td><?php echo date_default_timezone_get(); ?></td></tr>
                                    </table>
                                </div>
                                <div class="col-md-6">
                                    <table class="table table-sm">
                                        <tr><td><strong>上传限制：</strong></td><td><?php echo ini_get('upload_max_filesize'); ?></td></tr>
                                        <tr><td><strong>内存限制：</strong></td><td><?php echo ini_get('memory_limit'); ?></td></tr>
                                        <tr><td><strong>POST限制：</strong></td><td><?php echo ini_get('post_max_size'); ?></td></tr>
                                        <tr><td><strong>最大执行时间：</strong></td><td><?php echo ini_get('max_execution_time'); ?>秒</td></tr>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-lg-4">
                    <!-- 快速统计 -->
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5 class="mb-0">
                                <i class="bi bi-graph-up"></i> 快速统计
                            </h5>
                        </div>
                        <div class="card-body">
                            <?php
                            // 获取统计信息
                            $stmt = $db->query("SELECT 
                                COUNT(*) as total_users,
                                COUNT(CASE WHEN status = 1 THEN 1 END) as active_users,
                                COUNT(CASE WHEN is_admin = 1 THEN 1 END) as admins
                                FROM users");
                            $userStats = $stmt->fetch();
                            
                            $stmt = $db->query("SELECT 
                                COUNT(*) as total_orders,
                                COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending_orders,
                                COUNT(CASE WHEN status = 'settled' THEN 1 END) as settled_orders,
                                COUNT(CASE WHEN status = 'refunded' THEN 1 END) as refunded_orders,
                                SUM(CASE WHEN status = 'settled' AND settlement_amount > 0 THEN settlement_amount ELSE 0 END) as total_settlement
                                FROM orders");
                            $orderStats = $stmt->fetch();
                            ?>
                            
                            <div class="row g-3">
                                <div class="col-6">
                                    <div class="text-center">
                                        <h4 class="text-primary"><?php echo $userStats['total_users']; ?></h4>
                                        <p class="text-muted small mb-0">总用户数</p>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="text-center">
                                        <h4 class="text-success"><?php echo $userStats['active_users']; ?></h4>
                                        <p class="text-muted small mb-0">活跃用户</p>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="text-center">
                                        <h4 class="text-info"><?php echo $orderStats['total_orders']; ?></h4>
                                        <p class="text-muted small mb-0">总订单数</p>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="text-center">
                                        <h4 class="text-warning"><?php echo $orderStats['pending_orders']; ?></h4>
                                        <p class="text-muted small mb-0">待处理</p>
                                    </div>
                                </div>
                                <div class="col-12">
                                    <div class="text-center border-top pt-3">
                                        <h4 class="text-success">¥<?php echo number_format($orderStats['total_settlement'], 2); ?></h4>
                                        <p class="text-muted small mb-0">总结算金额</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 使用说明 -->
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0">
                                <i class="bi bi-question-circle"></i> 使用说明
                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="small">
                                <h6>管理员操作指南：</h6>
                                <ul class="mb-3">
                                    <li>定期查看待处理订单并及时处理</li>
                                    <li>处理订单时可添加结算信息和截图</li>
                                    <li>用户收款码可在用户详情中查看</li>
                                    <li>可批量操作订单状态</li>
                                </ul>
                                
                                <h6>推送通知设置：</h6>
                                <ul class="mb-3">
                                    <li>管理员可设置PushPlus密钥接收新订单通知</li>
                                    <li>用户可自主设置是否接收状态变更通知</li>
                                    <li>推送通知可选择性开启，默认关闭</li>
                                </ul>
                                
                                
                            </div>
                        </div>
                    </div>
                </div>
            </div>


<?php include __DIR__ . '/footer.php'; ?>

<script>
// 测试快递查询连接
function testExpressConnection() {
    const button = event.target;
    const originalText = button.innerHTML;
    button.innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span> 测试中...';
    button.disabled = true;
    
    fetch('api/express_query.php?action=test_connection')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showToast('连接测试成功！接口响应正常。', 'success');
            } else {
                let message = '连接测试失败：';
                if (data.data && data.data.http_code) {
                    message += ` HTTP ${data.data.http_code}`;
                }
                if (data.data && data.data.error) {
                    message += ` - ${data.data.error}`;
                }
                showToast(message, 'danger');
            }
        })
        .catch(error => {
            showToast('连接测试请求失败：' + error.message, 'danger');
        })
        .finally(() => {
            button.innerHTML = originalText;
            button.disabled = false;
        });
}

// 检查快递查询余额
function checkExpressBalance() {
    const button = event.target;
    const originalText = button.innerHTML;
    button.innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span> 检查中...';
    button.disabled = true;
    
    fetch('api/express_query.php?action=check_balance')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showToast(`当前余额: ¥${data.balance}`, 'success');
                setTimeout(() => {
                    location.reload();
                }, 1500);
            } else {
                showToast('余额查询失败: ' + data.message, 'danger');
                button.innerHTML = originalText;
                button.disabled = false;
            }
        })
        .catch(error => {
            showToast('请求失败: ' + error.message, 'danger');
            button.innerHTML = originalText;
            button.disabled = false;
        });
}

// 简单的提示函数
function showToast(message, type = 'info') {
    // 创建临时提示
    const toast = document.createElement('div');
    toast.className = `alert alert-${type} alert-dismissible fade show`;
    toast.style.position = 'fixed';
    toast.style.top = '20px';
    toast.style.right = '20px';
    toast.style.zIndex = '9999';
    toast.style.minWidth = '300px';
    toast.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(toast);
    
    // 自动移除
    setTimeout(() => {
        if (toast.parentNode) {
            toast.parentNode.removeChild(toast);
        }
    }, 5000);
}
</script>